package com.hzit.alipayfront.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.hzit.alipayfront.config.AlipayConfig;
import com.hzit.paycommon.paycommonapi.aliapy.AliapyTradeQueryReq;
import com.hzit.paycommon.paycommonapi.aliapy.AlipayPrePayReq;
import com.hzit.paycommon.paycommonapi.aliapy.AlipayWapPayReq;
import com.hzit.paycommon.paycommonapi.aliapy.resp.AlipayPrePayRespData;
import com.hzit.paycommon.paycommonapi.aliapy.resp.AlipayTradeQueryRespData;
import com.hzit.paycommon.paycommonapi.aliapy.resp.AlipayWapPayRespData;
import com.hzit.paycommon.paycommonapi.resp.RespVo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 支付宝的支付接口
 */
@RestController
@RequestMapping("/alipay")
public class AliapyPaymentController {


    AlipayConfig alipayConfig = new AlipayConfig();

    /**
     * 支付宝二维码支付，返回二维码地址
     * @param paymentReq
     */
    @RequestMapping("/tradePre")
    public RespVo<AlipayPrePayRespData> tradePre(@RequestBody AlipayPrePayReq paymentReq){
        //对接支付宝
        RespVo<AlipayPrePayRespData>  respVo = new RespVo<AlipayPrePayRespData>();

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getUrl(),alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),"json","GBK",alipayConfig.getAlipayPubKey(),"RSA2");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(paymentReq.getNotifyUrl());
        request.setReturnUrl(paymentReq.getReturnUrl());
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no",paymentReq.getSerialNum());
        bizContent.put("total_amount",paymentReq.getAmount());
        bizContent.put("subject",paymentReq.getSubject());
        request.setBizContent(bizContent.toJSONString());
        try {
            AlipayTradePrecreateResponse response = alipayClient.execute(request);

            System.out.println("getCode = " + response.getCode());
            System.out.println("getSubCode = " + response.getSubCode());



            System.out.println("msg = " + response.getMsg());
            System.out.println("qrCode = " + response.getQrCode());
            if(!"10000".equals(response.getCode())){
                respVo.setMsg(response.getMsg());
                respVo.setCode(-1);
                return respVo;
            }

//            if(!"ACQ.TRADE_HAS_SUCCESS".equals(response.getSubCode())){
//                respVo.setMsg(response.getSubMsg());
//                respVo.setCode(-1);
//                return respVo;
//            }

            AlipayPrePayRespData  respData = new AlipayPrePayRespData();
            respData.setQrCode(response.getQrCode());
            respVo.setData(respData);
            return respVo;

        } catch (AlipayApiException e) {
            e.printStackTrace();
            respVo.setMsg(e.getErrMsg());
            respVo.setCode(-1);
            return respVo;

        }

    }

    /**
     * 手机网站支付H5页面
     * @param paymentReq
     */
    @RequestMapping("/wapPay")
    public RespVo<AlipayWapPayRespData> tradeWap(@RequestBody AlipayWapPayReq paymentReq){

        RespVo<AlipayWapPayRespData> respDataRespVo = new RespVo<AlipayWapPayRespData>();

        //1.使用支付宝的sdk封装参数
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getUrl(),alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),"json","UTF-8",alipayConfig.getAlipayPubKey(),"RSA2");
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setReturnUrl(paymentReq.getReturnUrl()); //支付成功跳转的页面
        request.setNotifyUrl(paymentReq.getNotifyUrl()); //异步通知地址，修改流水状态。

        JSONObject bizContent = new JSONObject();
        bizContent.put("body","66");
        bizContent.put("subject",paymentReq.getSubject());
        bizContent.put("out_trade_no",paymentReq.getSerialNum());
        bizContent.put("total_amount",paymentReq.getAmount());
        bizContent.put("product_code",paymentReq.getProductCode());
        bizContent.put("quit_url",paymentReq.getQuickUrl());  //TODO 用户付款中途退出返回商户网站的地址
        request.setBizContent(bizContent.toJSONString());

        try {
            //2.请求到支付宝，拿到支付宝返回的form表单
            AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
            System.out.println("msg = " + response.getMsg());
            System.out.println("body = " + response.getBody());

            if(!"10000".equals(response.getCode())){
                respDataRespVo.setMsg(response.getMsg());
                respDataRespVo.setCode(-1);
                return respDataRespVo;
            }

            AlipayWapPayRespData  respData = new AlipayWapPayRespData();
            respData.setUrl(response.getBody());
            respDataRespVo.setData(respData);

            return respDataRespVo;
        } catch (AlipayApiException e) {
            e.printStackTrace();
            respDataRespVo.setMsg(e.getErrMsg());
            respDataRespVo.setCode(-1);
            return respDataRespVo;
        }

    }


    /**
     * 支付宝交易查询接口
     * @param tradeQueryReq
     */
    @RequestMapping("/tradeQuery")
    public RespVo<AlipayTradeQueryRespData> tradeQuery(@RequestBody AliapyTradeQueryReq tradeQueryReq){

        RespVo<AlipayTradeQueryRespData>  respDataRespVo = new RespVo<AlipayTradeQueryRespData>();

        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getUrl(),alipayConfig.getAppId(),
                alipayConfig.getPrivateKey(),"json","UTF-8",alipayConfig.getAlipayPubKey(),"RSA2");
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        //json对象
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("out_trade_no",tradeQueryReq.getOutTradeNo());
        jsonObject.put("trade_no",tradeQueryReq.getTradeNO());
        request.setBizContent(jsonObject.toJSONString());

        try {
            AlipayTradeQueryResponse response = alipayClient.execute(request);

            if(!"10000".equals(response.getCode())){
                respDataRespVo.setCode(-1);
                respDataRespVo.setMsg(respDataRespVo.getMsg());
                return respDataRespVo;
            }

            AlipayTradeQueryRespData queryRespData = new AlipayTradeQueryRespData();
//          queryRespData.setAppId(response.get); 配置文件
//          queryRespData.setGmtPayment(response.getp);
            queryRespData.setOutTradeNo(response.getOutTradeNo());
            queryRespData.setTradeNo(response.getTradeNo());
            queryRespData.setTotalAmount(response.getPayAmount());
            queryRespData.setTradeStatus(response.getTradeStatus());
            return respDataRespVo;
        } catch (AlipayApiException e) {
            e.printStackTrace(); //TODO
            respDataRespVo.setCode(-1);
            respDataRespVo.setMsg(e.getErrMsg());
            return respDataRespVo;
        }


    }




    public static void main(String[] args) {

        AlipayWapPayReq paymentReq = new AlipayWapPayReq();

        paymentReq.setAmount("100");
        paymentReq.setSerialNum(String.valueOf(System.currentTimeMillis()));
        paymentReq.setNotifyUrl("http://www.baidu.com");
        paymentReq.setReturnUrl("http://www.baidu.com");
        paymentReq.setSubject("测试");
        new AliapyPaymentController().tradeWap(paymentReq);

    }

    }
